'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 宝箱功能
 * @author sundbcn@gmail.com (sun debing)
 */

var async = require('async');
var moment = require('moment');
var _ = require('lodash');
var Code = require('../../../consts/code');
var moduleType = require('../../../consts/moduleType');
var operationType = require('../../../consts/operationType');
var PlayerManager = require('../../../libs/playerManager');
var dataApi = require('../../../libs/dataApi');
var rewardService = require('../../../services/rewardService');
var roleService = require('../../../services/roleService');
var luckyBoxConf = require('../../../config/luckyBoxConf.js');
var soldierConf = require('../../../config/soldierConf.js');
var marqueeConf = require('../../../config/marqueeConf.js');
var taskService = require('../../../services/taskService.js');
var marqueeModel = require('../../../models/marqueeModel.js');

module.exports = function (app) {
    return new Handler(app);
};

var Handler = function (app) {
    this.app = app;
};

/**
 * 领取宝箱奖励
 */
Handler.prototype.receiveReward = function (msg, session, next) {
    var role_id = session.uid;
    var box_id = msg.box_id;
    if (!box_id) {
        return next(null, {
            code: Code.PARAM_ERROR
        });
    }

    var reward_list = [];
    var luckyBox_list = [];
    var is_open_free;
    var fixed_reward = [luckyBoxConf.getConf(box_id)];
    // jshint maxstatements:100
    // jshint maxdepth: 10
    var player_manager = new PlayerManager(role_id);
    async.waterfall(
        [

            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(
                    ['role', 'friend', 'bag', 'soldier', 'vip', 'build', 'task', 'daily_task', 'achieve', 'tech', 'luckyBox', 'sevenDayActivity', 'accrued'],
                    cb
                );
            },
            function (cb) {
                var lucky_box_model = player_manager.luckyBox;
                var role_model = player_manager.role;
                var friend_model = player_manager.friend;
                is_open_free = luckyBoxConf.getConf(box_id).open_pick;

                //  增加免费开关    0  没有免费    1   有免费
                if (!is_open_free) {
                    // 关闭免费功能
                    // 钻石领取奖励
                    var sub_diamond = luckyBoxConf.getConf(box_id).cost_point;
                    if (box_id == 2) {
                        if (!friend_model.subFriendshipValue(sub_diamond)) {
                            return next(null, {
                                code: Code.FRIENDSHIP_VALUE_NOT
                            });
                        }
                    } else {
                        if (!roleService.subDiamond(player_manager, moduleType.MDL_ACT_LUCKY_BOX, operationType.OPR_ACT_LUCKY_BOX_OPEN, sub_diamond, box_id)) {
                            return next(null, {
                                code: Code.USER_DIAMOND_NOT_ENOUGH
                            });
                        }
                    }

                    // 发放固定奖励
                    _fixedReward(player_manager, box_id);

                    // 发放奖励
                    if (+box_id !== 1) {
                        reward_list = _reward(player_manager, box_id);
                    }

                    if (box_id == 1) {
                        var conf = dataApi.lucky_box_form.findById(box_id);
                        _.some(conf, function (conf_item) {
                            if (!!conf_item.must_pick_num) {
                                if (!!_saveNum(lucky_box_model, conf_item.must_pick_num)) {
                                    var quality_list = luckyBoxConf.getQualityItem(box_id, conf_item.quality);
                                    var random_num = _.random(0, quality_list.length - 1);

                                    // 发放固定奖励
                                    _fixedReward(player_manager, box_id);
                                    reward_list = [quality_list[random_num]];
                                    rewardService.addRewardListToRole(player_manager, reward_list, moduleType.MDL_ACT_LUCKY_BOX, operationType.OPR_ACT_LUCKY_BOX_OPEN);
                                } else {

                                    // 发放固定奖励
                                    _fixedReward(player_manager, box_id);

                                    // 发放奖励
                                    reward_list = _reward(player_manager, box_id);
                                }

                            }
                        });
                    }
                } else {
                    // 钻石领取奖励
                    var sub_diamond1 = luckyBoxConf.getConf(box_id).cost_point;

                    // 是否在免费时间如果免费扣次数
                    if (!!lucky_box_model.isFree(box_id) && !!lucky_box_model.subFreeNum(box_id)) {

                        // 发放固定奖励
                        _fixedReward(player_manager, box_id);

                        // 发放奖励
                        reward_list = _reward(player_manager, box_id);

                    } else {
                        // 扣资源
                        if (box_id == 2) {
                            if (!friend_model.subFriendshipValue(sub_diamond1)) {
                                return next(null, {
                                    code: Code.FRIENDSHIP_VALUE_NOT
                                });
                            }
                        } else {
                            if (!roleService.subDiamond(player_manager, moduleType.MDL_ACT_LUCKY_BOX, operationType.OPR_ACT_LUCKY_BOX_OPEN, sub_diamond1, box_id)) {
                                return next(null, {
                                    code: Code.USER_DIAMOND_NOT_ENOUGH
                                });
                            }
                        }

                        // 发放固定奖励
                        _fixedReward(player_manager, box_id);

                        // 发放奖励
                        if (+box_id !== 1) {
                            reward_list = _reward(player_manager, box_id);
                        }

                        if (box_id == 1) {
                            var conf_two = dataApi.lucky_box_form.findById(box_id);
                            _.some(conf_two, function (conf_item) {
                                if (!!conf_item.must_pick_num) {
                                    if (!!_saveNum(lucky_box_model, conf_item.must_pick_num)) {
                                        var quality_list = luckyBoxConf.getQualityItem(box_id, conf_item.quality);
                                        var random_num = _.random(0, quality_list.length - 1);

                                        // 发放固定奖励
                                        _fixedReward(player_manager, box_id);
                                        reward_list = [quality_list[random_num]];
                                        rewardService.addRewardListToRole(player_manager, reward_list, moduleType.MDL_ACT_LUCKY_BOX, operationType.OPR_ACT_LUCKY_BOX_OPEN);
                                    } else {

                                        // 发放固定奖励
                                        _fixedReward(player_manager, box_id);

                                        // 发放奖励
                                        reward_list = _reward(player_manager, box_id);
                                    }

                                }
                            });
                        }
                    }
                }

                luckyBox_list = lucky_box_model.getLuckyBoxQueueList();

                // 幸运宝箱次数统计
                taskService.addCompleteLuckyBoxNum(player_manager);
                player_manager.save(cb);
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            return next(null, {
                code: Code.OK,
                result: {
                    reward_list: reward_list,
                    fixed_reward: fixed_reward,
                    luckyBox_list: luckyBox_list
                }
            });
        }
    );
};

// 记录单抽次数
var _saveNum = function (lucky_box_model, num) {
    //
    return lucky_box_model.addOnlyReceiveNum(num);
};

// 发放固定奖励
var _fixedReward = function (player_manager, box_id) {
    if (box_id != 2) {
        var fixed_reward1 = [luckyBoxConf.getConf(box_id)];
        rewardService.addRewardListToRole(player_manager, fixed_reward1, moduleType.MDL_ACT_LUCKY_BOX, operationType.OPR_ACT_LUCKY_BOX_OPEN);
    }
};

// 发放奖励
var _reward = function (player_manager, box_id) {
    var reward_list = [];
    var reward_list1 = luckyBoxConf.luckyList(box_id);
    reward_list = rewardService.addRewardListToRole(player_manager, reward_list1, moduleType.MDL_ACT_LUCKY_BOX, operationType.OPR_ACT_LUCKY_BOX_OPEN);

    var string = '';
    var item_list = marqueeConf.getMsgConf(10);
    var itme_conf = marqueeConf.getConf(10);
    _.each(reward_list, function (reward_item) {

        if (reward_item.reward_type == 25 && reward_item.quality >= 4) {
            var soldier_name = soldierConf.getSoldierStarConf(reward_item.reward, 1).name;
            if (reward_item.quality === 5) {
                //  [#FF6633]name[-]
                string += '[FF6633]' + soldier_name + '[-],';
            }
            if (reward_item.quality === 4) {
                //  [#FF00CC]name[-]
                string += '[FF00CC]' + soldier_name + '[-],';
            }
        }
    });

    // 加入走马灯信息到数据库
    if (!!string) {
        var str = item_list[0].format;
        var reg = /name/;
        var name_value = player_manager.role.getName();
        var text = str.replace(reg, name_value);
        var regg = /soldier/;
        var text1 = text.replace(regg, string);
        console.log('text1:', text1);
        var list = ({
            sort_id: itme_conf.priority,
            text: text1,
            is_time: itme_conf.fixed_time,
            times: itme_conf.times,
            interval_time: itme_conf.time
        });
        marqueeModel.create(list, function (err, module) {

        });

    }
    return reward_list;
};

/**
 * 领取宝箱列表
 */
Handler.prototype.list = function (msg, session, next) {
    var role_id = session.uid;
    var luckyBox_list = [];

    var player_manager = new PlayerManager(role_id);
    async.waterfall(
        [

            function (cb) {
                player_manager.refreshData(cb);
            },
            function (cb) {
                player_manager.getModel(
                    ['role', 'bag', 'vip', 'build', 'task', 'daily_task', 'achieve', 'tech', 'luckyBox', 'sevenDayActivity', 'accrued'],
                    cb
                );
            },
            function (cb) {
                var lucky_box_model = player_manager.luckyBox;
                var role_model = player_manager.role;
                luckyBox_list = lucky_box_model.getLuckyBoxQueueList();
                player_manager.save(cb);
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return next(null, {
                    code: Code.FAIL
                });
            }
            return next(null, {
                code: Code.OK,
                result: {
                    luckyBox_list: luckyBox_list
                }
            });
        }
    );
};
